//
//  TeacherPostGrouRecordViewController.m
//  LoveDraw
//
//  Created by 零零壹 on 2017/7/20.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "TeacherPostGrouRecordViewController.h"
#import "JFImagePickerController.h"
#import "animationView.h"

@interface TeacherPostGrouRecordViewController ()<JFImagePickerDelegate,UITextViewDelegate,UIGestureRecognizerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong) UITextView *textView;
@property (nonatomic,strong) NSString *placehoder;
@property (nonatomic,strong) UIButton *btnDosubmit;
@property (nonatomic,strong) UIView *thumbsView;
@property(nonatomic,strong)UIImage *uploadimage;
@end

@implementation TeacherPostGrouRecordViewController
{
    NSMutableArray *photos;
    UICollectionView *photosList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"添加成长记录";
    self.view.backgroundColor = UIColors(0xF8F8F8);
    self.placehoder = @"请输入要留言的内容";
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(10, 74, MAIN_SCREEN_WIDTH-20, 150) textContainer:nil];

    self.textView.backgroundColor = [UIColor whiteColor];
    [self.textView setText:self.placehoder];
    [self.textView setFont:[UIFont systemFontOfSize:16]];
    [self.textView setTextColor:[UIColor grayColor]];
    self.textView.delegate = self;
    [self.view addSubview:self.textView];

    self.btnDosubmit = [[UIButton alloc]init];
    [self.btnDosubmit setTitle:@"提交" forState:UIControlStateNormal];
    [self.btnDosubmit setBackgroundColor:UIColors(MainColor)];
    [self.btnDosubmit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.btnDosubmit.layer.cornerRadius = 2.0;
    [self.view addSubview:self.btnDosubmit];

    [self.btnDosubmit mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.bottom.equalTo(self.view.mas_bottom).offset(-10);
        make.height.mas_equalTo(44);
    }];
    [self.btnDosubmit addTarget:self action:@selector(doneAction:) forControlEvents:UIControlEventTouchUpInside];

    //代码开始
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeAll;
    photos = [[NSMutableArray alloc] init];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 5;
    NSInteger size = (MAIN_SCREEN_WIDTH-40)/5;
    if (size%2!=0) {
        size-=1;
    }
    flowLayout.itemSize = CGSizeMake(size, size);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);

    photosList = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
    photosList.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    photosList.scrollIndicatorInsets = photosList.contentInset;
    photosList.delegate = self;
    photosList.dataSource = self;
    photosList.backgroundColor = [UIColor clearColor];
    photosList.alwaysBounceVertical = YES;

    [self.view addSubview:photosList];
    [photosList registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"imagePickerCell"];
    [photosList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.top.equalTo(self.textView.mas_bottom).offset(10);
        make.bottom.equalTo(self.btnDosubmit.mas_top);
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(photos.count==0){
        return 1;
    }else{
        return photos.count+1;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imagePickerCell" forIndexPath:indexPath];

    if(photos.count==indexPath.row){
        UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:1];
        if (!imgView) {
            imgView = [[UIImageView alloc] initWithFrame:cell.bounds];
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            imgView.clipsToBounds = YES;
            imgView.tag = 1;
            [cell addSubview:imgView];
        }
        [imgView setImage:[UIImage imageNamed:@"upload"]];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(upladImage:)];
        [cell addGestureRecognizer:tap];
    }else{
        ALAsset *asset = photos[indexPath.row];
        UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:1];
        if (!imgView) {
            imgView = [[UIImageView alloc] initWithFrame:cell.bounds];
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            imgView.clipsToBounds = YES;
            imgView.tag = 1;
            [cell addSubview:imgView];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(preview:)];
            [cell addGestureRecognizer:tap];
        }
        cell.tag = indexPath.item;

        [[JFImageManager sharedManager] thumbWithAsset:asset resultHandler:^(UIImage *result) {
            if (cell.tag==indexPath.item)
            {
                //  NSData *data = UIImageJPEGRepresentation(result, 1);
                imgView.image = result;
            }
        }];
    }
    return cell;
}
-(void)upladImage:(UITapGestureRecognizer *)tap{

    
    JFImagePickerController *picker = [[JFImagePickerController alloc] initWithRootViewController:nil];
    picker.pickerDelegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)preview:(UITapGestureRecognizer *)tap{


    UIView *temp = tap.view;
    JFImagePickerController *picker = [[JFImagePickerController alloc] initWithPreviewIndex:temp.tag];
    picker.pickerDelegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}


#pragma mark - ImagePicker Delegate
- (void)imagePickerDidFinished:(JFImagePickerController *)picker{


    [photos removeAllObjects];
    [photos addObjectsFromArray:picker.assets];

    [photosList reloadData];
    [self imagePickerDidCancel:picker];
}

- (void)imagePickerDidCancel:(JFImagePickerController *)picker
{

    [picker dismissViewControllerAnimated:YES completion:nil];
}


// 提交留言
- (IBAction)doneAction:(UIButton *)btn {
    if([self.textView.text isEqualToString:self.placehoder]){
        [HUD showText:@"留言不能为空" AfterTime:1];
    }else
    {
        [self postMessage];
    }
}

-(void)postMessage
{
    [animationView showInView:self.view];

    dispatch_queue_t cycQueue = dispatch_queue_create("Renwu", DISPATCH_QUEUE_CONCURRENT);
    dispatch_sync(cycQueue, ^{
        if (photos.count==0)
        {
            NSString *content = self.textView.text;
            [self DopostAllinfo:content arr:[@[] mutableCopy]];
        }else
        {
            NSString *content = self.textView.text;
            NSMutableArray *indexArr = [@[]mutableCopy];
            for (NSInteger i = 0; i < photos.count; i++)
            {
                ALAsset *asset = photos[i];
                UIImage *upimage = [ASSETHELPER getImageFromAsset:asset type:ASSET_PHOTO_FULL_RESOLUTION];


                [[UploadImage sharedClient]doUploadImage:@"/index.php?g=App&m=Index&a=uploadsImgone" parameters:@{@"uid":[[NSUserDefaults standardUserDefaults]objectForKey:kUserId],@"access_token":[[NSUserDefaults standardUserDefaults]objectForKey:kAccessToken]} image:upimage successBlock:^(id responseBody)
                 {
                     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseBody options:0 error:nil];
                     if ([dic[@"flag"]isEqualToString:@"Success"]) {
                         NSDictionary *imageAndIndexDic = @{@"index":[NSString stringWithFormat:@"%ld",i],@"imageUrl":dic[@"data"]};

                         [indexArr addObject:imageAndIndexDic];

                         if (indexArr.count == photos.count)
                         {
                             [animationView dismiss];
                             [self DopostAllinfo:content arr:indexArr];
                         }
                     }else
                     {
                         [animationView dismiss];
                         [HUD showText:dic[@"Success"] AfterTime:1];
                     }
                 } failureBlock:^(NSString *error)
                 {
                     [animationView dismiss];
                 }];
            }
        }
    });
}

-(void)DopostAllinfo:(NSString *)content arr:(NSMutableArray *)imageArr
{

    NSMutableArray *upimageArr = [NSMutableArray array];

    for (NSInteger i = 0; i<imageArr.count; i++)
    {
        for (NSDictionary *imageDic in imageArr)
        {
            if ([imageDic[@"index"] isEqualToString:[NSString stringWithFormat:@"%ld",i]])
            {
                [upimageArr addObject:imageDic[@"imageUrl"]];
            }
        }
    }

    [RequestManager NormalRequstWithUrl:@"/index.php?g=App&m=TeacherGrowth&a=addLog" parmDic:@{@"sid":self.sid,@"contents":content,@"thumbs":upimageArr,@"tid":[[NSUserDefaults standardUserDefaults]objectForKey:@"tid"]} requestType:RequestPOST Success:^(id data)
     {

         [self.navigationController popViewControllerAnimated:YES];
     } error:^(NSError *error)
     {

     }];
}

-(void)closeEnter{
    [self.textView resignFirstResponder];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1){
        textView.text = self.placehoder;
        textView.textColor = [UIColor grayColor];
    }
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:self.placehoder]){
        textView.text=@"";
        textView.textColor=[UIColor blackColor];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
